﻿#include "dwgline.h"
#include<QPoint>
#include <cmath>
DwgLine::DwgLine(QObject *parent)
     : DwgObject{parent}
{
}
 void DwgLine::SetData(QPointF pt1, QPointF pt2)
{
    mStartPt = pt1,mEndPt = pt2;
}
void DwgLine::Draw(QPainter *painter)
{
    //=========抑制线宽变化========//
    QPen pen;
    pen.setCosmetic(true);       // 允许线宽缩放
    pen.setWidth(1);             // 使用逻辑线宽
    painter->setPen(pen);
    //==========选择+删除=========//
    if(mDeleteed) return;
    if(mSelected)
    {
        painter->setPen(Qt::red);
    }

    painter->drawLine(mStartPt,mEndPt);
    painter->setPen(Qt::black);
}

//==选择+删除==//
void DwgLine::Select(QPointF pt)
{
    // 直线起点为mStartPt，终点为mEndPt
    qreal x0 = pt.x();
    qreal y0 = pt.y();
    qreal x1 = mStartPt.x();
    qreal y1 = mStartPt.y();
    qreal x2 = mEndPt.x();
    qreal y2 = mEndPt.y();

    // 计算点到直线的距离
    qreal dist =fabs((y2-y1)*x0 - (x2-x1)*y0 + x2*y1 - y2*x1) /
                sqrt((y2-y1)*(y2-y1) + (x2-x1)*(x2-x1));

    // 检查点是否在直线段范围内
    qreal dotProduct = (x0-x1)*(x2-x1) + (y0-y1)*(y2-y1);
    qreal lengthSquared = (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1);

    // 如果距离小于3像素且在直线段范围内(或延长线附近)，则选中
    if(dist < 3 && dotProduct >= 0 && dotProduct <= lengthSquared)
        mSelected = true;
}
